package com.jn.algorithm.day012.question38;

/**
 * @author 江南大学1033190417
 * @date 2022/4/27 16:41
 */
public class Solution {
    public String countAndSay(int n) {
        String temp = "1";
        for (int i = 1; i < n; i++) {
            temp = parse(temp);
        }
        return temp;
    }

    public String parse(String input) {
        if (input.length() == 1) {
            return 1 + input;
        }
        StringBuilder res = new StringBuilder();
        int length = input.length();
        char temp = '*';
        int count = 0;
        for (int i = 0; i < length; i++) {
            char c = input.charAt(i);
            if (i == 0) {
                temp = c;
                count = 1;
                continue;
            }
            if (i == length - 1) {
                if (c == input.charAt(i - 1)) {
                    ++count;
                    res.append(count).append(temp);
                } else {
                    res.append(count).append(temp);
                    res.append(1).append(c);
                }
                continue;
            }
            if (temp != c) {
                res.append(count).append(temp);
                temp = c;
                count = 1;
            } else {
                count++;
            }
        }
        return res.toString();
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.countAndSay(4));
    }
}
